<script setup lang="ts">
import type { InterviewQuestionCategory } from '#/api/interview/category/model';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { useSortable } from '@vben-core/composables';

import { Card } from 'ant-design-vue';

import { updateCategoryOrder } from '#/api/interview/category';

defineOptions({
  name: 'CategorySortModal',
});

const emit = defineEmits<{ reload: [] }>();

const categoryList = ref<InterviewQuestionCategory[]>([]);

const [BasicModal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: handleConfirm,
  onOpenChange(isOpen) {
    if (isOpen) {
      // 模态框打开时初始化数据
      const { categories } = modalApi.getData() as {
        categories: InterviewQuestionCategory[];
      };

      // 为每个分类添加序号，从1开始
      categoryList.value = categories.map((item, index) => ({
        ...item,
        orderNum: index + 1,
      }));

      // 等待DOM更新后初始化拖拽功能
      setTimeout(initSortable, 100);
    } else {
      // 模态框关闭时销毁拖拽功能
      if (sortableInstance) {
        sortableInstance.destroy();
      }
    }
  },
});

let sortableInstance: any = null;

// 初始化拖拽功能
async function initSortable() {
  const el = document.querySelector('.category-sortable-list');
  if (!el) return;

  const { initializeSortable } = useSortable(el as HTMLElement, {
    animation: 300,
    chosenClass: 'chosen',
    dragClass: 'dragging',
    ghostClass: 'sortable-ghost',
    handle: '.category-sortable-item',
    onEnd: (evt: any) => {
      const { oldIndex, newIndex } = evt;
      if (oldIndex !== newIndex) {
        // 重新排序数组
        const movedItem = categoryList.value.splice(oldIndex, 1)[0];
        categoryList.value.splice(newIndex, 0, movedItem);

        // 更新所有项目的序号
        categoryList.value = categoryList.value.map((item, index) => ({
          ...item,
          orderNum: index + 1,
        }));
      }
    },
  });

  sortableInstance = await initializeSortable();
}

// 确认排序
async function handleConfirm() {
  try {
    modalApi.modalLoading(true);

    // 构造更新数据
    const updateData = categoryList.value.map((item) => ({
      categoryId: item.categoryId as number,
      orderNum: item.orderNum,
    }));

    // 调用API更新排序
    await updateCategoryOrder(updateData);

    // 关闭模态框
    modalApi.close();

    // 触发刷新事件
    emit('reload');
  } catch (error) {
    console.error('更新排序失败:', error);
  } finally {
    modalApi.modalLoading(false);
  }
}
</script>

<template>
  <BasicModal title="排序" width="600px">
    <div class="category-sortable-list space-y-2">
      <Card
        v-for="item in categoryList"
        :key="item.categoryId"
        class="category-sortable-item cursor-move transition-all duration-200 hover:shadow-md"
        :bordered="true"
      >
        <div class="flex items-center py-1">
          <div
            class="mr-3 flex h-4 w-4 cursor-move items-center justify-center rounded bg-gray-100"
          >
            <IconifyIcon
              class="text-gray-600"
              icon="ant-design:drag-outlined"
            />
          </div>
          <div class="flex-1 pl-4">
            <div class="font-medium">
              {{ item.categoryName }} / {{ item.categoryDescription }}
            </div>
          </div>
          <div class="pr-6 text-gray-400">#{{ item.orderNum }}</div>
        </div>
      </Card>
    </div>
  </BasicModal>
</template>

<style scoped>
:deep(.ant-card-body) {
  padding: 2px;
}

.chosen {
  z-index: 1000;
  box-shadow: 0 0 10px rgb(0 0 0 / 10%);
  transform: scale(1.02);
}

.dragging {
  box-shadow: 0 5px 15px rgb(0 0 0 / 20%);
  opacity: 0.8;
  transition: all 0.2s ease;
  transform: scale(1.02) rotate(2deg);
}

.sortable-ghost {
  background-color: #f0f2f5;
  opacity: 0.6;
  transition: all 0.3s ease;
  transform: scale(0.98);
}

.category-sortable-item:hover {
  transform: translateY(-1px);
}

.category-sortable-item {
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
}
</style>
